// 获取文件输入元素
const fileInput = document.getElementById('imageUpload');
const resulMessage = document.getElementById('result');
const uploadedImage = document.getElementById("uploadedImage");
let resultFileName = "";

document.getElementById('uploadButton').addEventListener('click', () => {
    if (!resultFileName) {
        alert("Please upload an image first.");
        return;
    }
    recognize();
});

// 当文件被选择时上传文件
fileInput.addEventListener('change', (event) => {
    let local_file = event.target.files[0];
    uploadFiles(() => {
        uploadedImage.src = URL.createObjectURL(local_file);
        uploadedImage.style.display = 'block    ';
    });
});

/**
 * 上传文件函数
 * @param callback {Function | null}
 * @returns {void}
 */
// 上传文件函数
const uploadFiles = (callback) => {
    const files = fileInput.files;

    if (!files) {
        alert('Please select an image to upload.');
        return;
    }

    const formData = new FormData();
    formData.append('image', files[0]);

    // 使用 Fetch API 上传文件
    fetch('/api/upload', {
        method: 'POST',
        body: formData,
    })
        .then(response => {
            if (!response.ok) {
                // 如果状态码不是2xx，抛出错误
                return response.json().then(err => {
                    throw new Error(err.errors || 'Upload failed');
                });
            }
            return response.json();
        })
        .then(data => {
            resultFileName = data.data;
            resulMessage.innerHTML = `Upload successful: ${data.message}`;
            if (callback) callback();
            return data.data;
        })
        .catch(error => {
            resulMessage.innerHTML = `Upload failed: ${error.message}`;
        });
}


const recognize = () => {
    fetch('/api/recognize', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({filename: resultFileName}),
    })
        .then(response => response.json())
        .then(data => {
            console.log(data);
            resulMessage.innerHTML = `${data.output.choices[0].message.content[0].text}`;
        })
        .catch(error => {
            console.error(error);
            resulMessage.innerHTML = `Recognition failed: ${error}`;
        })
}